import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:my_flutter/demo_page.dart';

import 'battery_level_page.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      // home: const DemoPage(),
      home: const BatterLevelPage(title: 'My home page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static const platform = MethodChannel('com.sunricher.dancing_with_flutter/channel');
  String _message = "No message yet";

  @override
  void initState() {
    super.initState();
    _setupMethodChannel();
  }

  void _incrementCounter() {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              _message,
              style: Theme.of(context).textTheme.headlineMedium,
            ),
            ElevatedButton(onPressed: _sendDataToNative, child: const Text('Send data to Native')),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  Future<void> _setupMethodChannel() async {
    platform.setMethodCallHandler((call) async {
      switch (call.method) {
        case 'sendDataToFlutter':
          final Map<Object?, Object?> argsRaw = call.arguments;
          final Map<String, dynamic> args = Map<String, dynamic>.from(argsRaw);
          setState(() {
            _message = "Received from iOS: ${args['name']}, ${args['age']}";
          });
          return 'Data received by flutter';
        default:
          throw PlatformException(code: 'NOT_IMPLEMENTED', message: 'Method not implemented');
      }
    });
  }

  Future<void> _sendDataToNative() async {
    try {
      final result = await platform.invokeMethod('sendDataToNative', {'message': 'Hello from flutter'});
      setState(() {
        _message = result;
      });
    } catch (e) {
      setState(() {
        _message = 'Failed to send: $e';
      });
    }
  }
}
